/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package projetlif13.model.tournament;

import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import projetlif13.model.Game;
import projetlif13.model.IAPlayer;
import projetlif13.model.Player;
import projetlif13.model.puissance4.P4Game;
import projetlif13.model.puissance43D.P43DGame;
import projetlif13.model.tictactoe.TicGame;
import projetlif13.scene.GameScene;
import projetlif13.view.GameView;

/**
 *
 * @author yohan
 */
public class TournamentV2 {
    
    ArrayList<Player> players = new ArrayList<>();
    ArrayList<TournamentNodeV2> nodes = new ArrayList<>();
    int board;
    public static Player globalWinner;
    
    public TournamentV2(int board) {
        this.board = board;
    }
    
    public void addPlayer(Player p) {
        players.add(p);
    }
    
    public void init() {
        
        Player p1;
        Player p2;
        System.out.println(players.size() + " players registered for tournament next step");
        for (int i = 0; i < players.size(); i += 2) {
            p1 = players.get(i);
            if (i + 1 >= players.size() || players.size() == 1) {
                //le dernier joueur est seul on ne le met pas
                //on sort de la boucle for, nb impairs de joueurs...
                System.err.println(p1.getName() + " ne peux pas prendre part au tournois car il est seul.");
                TournamentNodeV2 tn = new TournamentNodeV2();
                tn.setWinner(p1);
                nodes.add(tn);
                break;
            } else {
                p2 = players.get(i + 1);
            }
            if (p1 != null && p2 != null) {
                System.out.println("Creating node with " + p1.getName() + " vs " + p2.getName());
                TournamentNodeV2 tn = new TournamentNodeV2();
                tn.setP1(p1);
                tn.setP2(p2);
                nodes.add(tn);
            }
        }
    }
    
    public Player playTournament() {
        for (TournamentNodeV2 node : nodes) {
            while (GameView.gameScene.isDraw() || GameView.gameScene.getWinner() == null) { //tant qu'il y a match null on recommance le noeud sinon on passera une fois dedans
                Game g = null;
                GameView.stopPreviousGame();
                switch (board) {
                    case GameScene.TYPE_P4:
                        g = new P4Game(node.getP1(), node.getP2());
                        break;
                    case GameScene.TYPE_P43D:
                        g = new P43DGame(node.getP1(), node.getP2());
                        break;
                    case GameScene.TYPE_TIC:
                        g = new TicGame(node.getP1(), node.getP2());
                        break;
                }
                GameScene.gv.setGame(g);
                GameView.gameScene.reinit();
                /*
                 * Tant que le winner de GameScene est null on attends.
                 */
                while (GameView.gameScene.getWinner() == null && !GameView.gameScene.isDraw()) {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(TournamentV2.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(TournamentV2.class.getName()).log(Level.SEVERE, null, ex);
                }
                
            }
            //si ya match null on relance sinon on créer un nouveau noeuds avec les deux nouveaux gagnant
            if (GameView.gameScene.getWinner() != null) {
                System.out.println("Winner is " + GameView.gameScene.getWinner().getName());
            } else {
                System.out.println("Round draw");
            }
            if (GameView.gameScene.getWinner() != null) {
                node.setWinner(GameView.gameScene.getWinner());
            }
            GameView.gameScene.setDraw(false);
            GameView.gameScene.setWinner(null);
            
        }
        //on à fait les noeuds, il faut reconstruire les noeuds avec les joueurs gagnants.
        players.clear();
        for (TournamentNodeV2 node : nodes) {
            players.add(node.getWinner());
        }
        
        if (players.size() == 1) {
            System.out.println("The GLOBLAL winner is " + players.get(0).getName());
            globalWinner = players.get(0);
            return globalWinner;
        } else {
            //reconstruction des nouveaux noeuds
            nodes.clear();            
            init();
            return playTournament(); //on retourne récursivment
        }
    }
}
